<template>
	<div class="game-container report-container addAgent-container">
			<div class="line-member"></div>
			<div class="addAgent-content">
				<div class="form-header">
					<span>升级总代申请资料</span>
					<span>
						<code style="color:#FF3B30;">*</code>
						{{ $t('common.add_dialog_tips') }}
					</span>
				</div>
				<el-form
					ref="validateForm"
					:model="formData"
					:rules="rules"
					label-width="130px"
					class="demo-formData"
				>
                <el-form-item
						:label="$t('common.choose_merchant') + ':'"
						prop="merchantId"
					>
						<el-col :span="12">
							<merchant-select
								style="width: 365px"
								v-model="formData.merchantId"
								:placeholder="$t('common.please_choose')"
							></merchant-select>
                            <span v-show="tipsMerchantShow" class="tips">
                                {{ tipsMerchantShow }}
                            </span>
						</el-col>
				</el-form-item>
                <el-form-item
					label="实际被转代理:"
					prop="proxyName"
				>
					<el-input
						v-model="formData.proxyName"
						size="medium"
						maxlength="11"
						:placeholder="$t('common.please_enter')"
						clearable
						style="width: 365px"
                        @change="() => {
                            tipsShow = null
							formData.creditQuotaType = undefined
							formData.accountType = undefined
                        }"
					></el-input>
					<span v-show="tipsShow && formData.proxyName" class="tips">{{ tipsShow }}</span>
					<el-button
						type="primary"
						style="margin-left: 20px"
                        :disabled="!formData.proxyName"
						@click="getOutlineInfo"
					>
						<i v-show="loadingT" class="el-icon-loading"></i>
						{{ $t('common.search') }}
					</el-button>
				</el-form-item>
                <el-form-item
                    :label="$t('agent.account_type') + ':'"
                    prop="accountType"
                >
                    <el-col :span="12">
                        <el-select
                            disabled
							style="width: 365px"
                            v-model="formData.accountType"
                            :placeholder="
                                $t('agent.rule_select_tip_agent_type')
                            "
                        >
                            <el-option
                                v-for="item in accountTypeArr"
                                :key="item.code"
                                :label="item.description"
                                :value="item.code"
                            ></el-option>
                        </el-select>
                    </el-col>
                </el-form-item>
				<el-form-item
					v-if="formData.creditQuotaType"
                    label="信用额度处置:"
                    prop="creditQuotaType"
                >
                    <el-col :span="12">
                        <el-select
							style="width: 365px"
                            v-model="formData.creditQuotaType"
                        >
								<el-option value="1" label="回收信用额度" />
                           		<el-option value="2" label="带走信用额度" />
                        </el-select>
                    </el-col>
                </el-form-item>
                <AgentRebates labelWidth="130px" ref="AgentRebates" :isEdit="true" />
                <el-form-item label="申请信息:" prop="applyRemark">
                    <el-col :span="12">
                        <el-input
							style="width: 365px"
                            v-model.trim="formData.applyRemark"
                            :rows="4"
                            show-word-limit
                            type="textarea"
                            minlength="4"
                            maxlength="50"
                        />
                    </el-col>
                </el-form-item>
                <el-form-item>
                    <el-button
                        type="primary"
                        :disabled="loading"
                        @click="submitForm('validateForm')"
                    >
                        {{ $t('common.submit') }}
                    </el-button>
                    <el-button @click="resetForm('validateForm')">
                        {{ $t('common.reset') }}
                    </el-button>
                </el-form-item>
				</el-form>
			</div>

			<el-dialog
				width="300px"
				:visible="!!eventId"
				:show-close="false"
				:close-on-click-modal="false"
				:destroy-on-close="true"
				title="升级总代资料提交成功"
			>
				<p>审核号：<a class="el-link el-link--primary" @click="goOpenProxyReview">{{ eventId }}</a> 等待审核结果</p>
				<div slot="footer" class="dialog-footer">
					<el-button type="primary" @click="eventId = undefined">
						返回
					</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>
import list from '@/mixins/list'
import AgentRebates from '@/components/AgentRebates'
import { notSpecial2, isHaveEmoji } from '@/utils/validate'
export default {
	components: {
		AgentRebates
	},
	mixins: [list],
	props: {
		agentLevel: {
			type: Array,
			default: () => []
		}
	},
	data() {
		return {
			loading: false,
            tipsShow: '',
            tipsMerchantShow: null,
            loadingT: false,
			eventId: undefined,
			commissionModel: undefined,
			formData: {
				proxyName: undefined,
                proxyId: undefined,
				password: undefined,
				maxLevels: undefined,
				accountType: undefined,
                applyRemark: undefined,
                creditQuotaType: undefined,
			}
		}
	},
	computed: {
		appIdArr() {
			return this.globalDics.appId || []
		},
		rules() {
            const testApplyInfo = (rule, value, callback) => {
				const isSpecial = !notSpecial2(String(value))
				const isRmoji = isHaveEmoji(String(value))
				if (isSpecial) {
					callback(new Error(this.$t('agent.rule_other_tip2')))
				} else if (isRmoji) {
					callback(new Error(this.$t('agent.rule_other_tip1')))
				} else if (!value) {
					callback(new Error(this.$t('agent.rule_input_tip_audit')))
				} else {
					callback()
				}
			}
			return {
                merchantId: [
					{
						required: true,
						message: this.$t('agent.rule_select_tip_merchant'),
						trigger: ['change', 'blur']
					}
				],
                proxyName: [
					{
						required: true,
						message: '请输入实际被转代理',
						trigger: ['change', 'blur']
					},
				],
                applyRemark: [
					{
						required: true,
						message: '请输入申请信息',
						trigger: ['change', 'blur']
					},
					// {
					// 	required: true,
					// 	validator: testApplyInfo,
					// 	trigger: 'blur'
					// },
					{
						min: 2,
						max: 50,
						message: this.$t('agent.rule_length_tip2-50'),
						trigger: 'blur'
					}
				]
            }
		},
        accountTypeArr() {
            const arr =
                (this.globalDics.accountType &&
                    JSON.parse(JSON.stringify(this.globalDics.accountType))) ||
                []
            return arr
        }
	},
	methods: {
		goOpenProxyReview () {
			this.$router.push({
				path: '/agent/agencyReview/upTopProxyAuditReview',
				query: {
					eventId: this.eventId
				}
			})
			this.eventId = undefined
		},
		formatParams() {
			const params = {
				...this.formData,
				type: 1,
				rebateRateList: this.$refs['AgentRebates'].getValues()
			}
			return params
		},
		async resetForm() {
			await this.$refs['validateForm'].resetFields()
			await this.$refs['AgentRebates'].resetFields()

			this.$refs['AgentRebates'].clearValidate('rebateRateTemplateId')
		},
        getOutlineInfo() {
			let lock = true
			const { proxyName, merchantId } = this.formData
			if (!merchantId) {
				this.tipsMerchantShow = this.$t(
					'agent.rule_select_tip_merchant'
				)
				return
			} else {
				this.tipsMerchantShow = null
			}
			if (lock) {
				this.loadingT = true
				this.$api
					.getProxyDetailQueryDetail({ userName: proxyName, merchantId })
					.then((res) => {
						lock = false
						this.loadingT = false
						if (res?.code === 200) {
							if (res.data) {
								this.tipsShow = null
								this.formData.accountType = res.data.accountType + ''
								this.formData.proxyId = res.data.id
								this.formData.commissionMode = res.data.commissionModel
								this.formData.commissionModel = res.data.commissionModel
								if(res.data.businessModel==2){
									this.formData.creditQuotaType = '1'
								}else{
									this.formData.creditQuotaType = undefined
								}
								this.commissionModel = res.data.commissionModel

								this.$nextTick(() => {
									if (this.commissionModel === 2){
										this.tipsShow =  '佣金模式代理不可转代'
									}
									
								})
							} else {
								this.tipsShow =
									res.msg ||
									this.$t('agent.interface_exceptions')
							}
						} else {
							this.tipsShow =
								res?.msg ||
								this.$t('agent.interface_exceptions')
						}
					})
					.catch(() => {
						this.loadingT = false
						this.tipsShow = this.$t('agent.rule_agent_tip')
						lock = false
					})

				setTimeout(() => {
					this.loadingT = false
					lock = true
				}, 1000)
			}
		},
		async validate() {
			return Promise.all([
				new Promise((resolve, reject) => {
					this.$refs['AgentRebates'].validate((err) => {
						if (err) {
							return resolve()
						}

						return reject()
					})
				}),
				new Promise((resolve, reject) => {
					this.$refs['validateForm'].validate((err) => {
						if (err) {
							return resolve()
						}
						return reject()
					})
				})
			])
		},
		async submitForm() {
			try {
				if (this.tipsShow) {
					return false
				}
				await this.validate()
				this.loading = true
				const res = await this.$api.upTopProxyAuditAddUpTopProxyAudit(
					this.formatParams()
				)
				if (res.code === 200) {
					this.eventId = res.data
					return
				}

				const blackCode = [-10001, -10002, -10003, -10004]
				if (blackCode.includes(res.code)) {
					this.$confirm(
						`${res.msg}，${this.$t('agent.prohibit_add')}！`,
						this.$t('agent.tip'),
						{
							confirmButtonText: this.$t('common.confirm'),
							type: 'warning',
							showCancelButton: false
						}
					)
				} else {
					this.$message({
						message:
							res?.msg || this.$t('agent.interface_exceptions'),
						type: 'error'
					})
				}
			} catch (err) {
				if (err === false) return
				throw err
			} finally {
				this.loading = false
			}
		}
	}
}
</script>
<style lang="scss" scoped>
::v-deep .el-dialog__header {
	text-align: center;
	color: #909399;
	font-weight: 700;
}
.addAgent-container {
	background-color: #f5f5f5;
	margin: 0;
	min-height: calc(100vh - 105px);
	.line-member {
		height: 50px;
	}
	.addAgent-content {
		width: 1100px;
		margin: 0 auto;
		display: flex;
		justify-content: center;
		align-items: center;
		background-color: #fff;
		position: relative;
		padding-top: 65px;
		padding-bottom: 65px;
		.form-header {
			height: 45px;
			line-height: 45px;
			span:nth-child(1) {
				position: absolute;
				left: 30px;
				top: 0;
				color: #666;
				font-size: 14px;
				font-weight: 700;
			}
			span:nth-child(2) {
				position: absolute;
				right: 30px;
				color: #999;
				font-weight: 400;
				font-size: 14px;
				top: 0;
			}
		}
		.tips {
			color: #f56c6c;
			font-size: 12px;
			line-height: 1;
			padding-top: 4px;
			position: absolute;
			top: 100%;
			left: 0;
		}
	}
	.addAgent-content::after {
		position: absolute;
		top: 45px;
		content: '';
		width: 100%;
		background-color: rgba(233, 233, 233, 1);
		height: 1px;
	}
}
</style>
